package com.moter.demo01.juc.component;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号量
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 8; i++) {
            new Thread(()->{
                try {
//                    boolean b=false;
//                    while(!b){
//                        b= semaphore.tryAcquire(1, TimeUnit.SECONDS);
//                    }
                    semaphore.acquire();

                    System.out.println(Thread.currentThread().getName()+"抢到车位了");
                    TimeUnit.SECONDS.sleep(4);
                    semaphore.release();
                    System.out.println(Thread.currentThread().getName()+"开走了");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
